package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Managelogs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service(version = "1.0.0")
public class DashboardApiImpl implements DashboardApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询日志表的数据
     *
     * @return
     */
    @Override
    public List<Managelogs> getManagelogsList(long startTme, long endTime) {
        //大于等于(gte),小于等于(lte)
        Query query = Query.query(Criteria.where("logTime").lte(endTime).gte(startTme));
        List<Managelogs> managelogsList = mongoTemplate.find(query, Managelogs.class);

        return managelogsList;
    }

    /**
     * 根据用户id查询日志表用户
     *
     * @param userId
     * @return
     */
    @Override
    public Managelogs getManagelogsByUserId(long startTme, long endTime, Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("logTime").lte(endTime).gte(startTme)
        );
        return this.mongoTemplate.findOne(query, Managelogs.class);
    }

    /**
     * 查询时间戳内的活跃用户数量,去重
     *
     * @param startTme 开始时间
     * @param endTime  结束时间
     * @return
     */
    @Override
    public Integer activeUsersCount(long startTme, long endTime) {
        Query query = Query.query(Criteria.where("logTime").lte(endTime).gte(startTme));
        List<Managelogs> managelogsList = mongoTemplate.find(query, Managelogs.class);
        List<Object> userIds = CollUtil.getFieldValues(managelogsList, "userId");
        List<Object> collect = userIds.stream().distinct().collect(Collectors.toList());
        return collect.size();
    }


}
